const App = getApp()
import { MineModel } from '../../../models/mine.js'
const ModelMine = new MineModel()
Page({
  data: {
    address: [],
    showArrow: false,
    iphoneX: App.globalData.isIphoneX,
    empty:false,
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar:false
  },
  onLoad: function(options) {
    this.setData({
      showArrow: options.form === 'account' ? false : true
    })
  },
  onShow() {
    // 重新获取数据
    this.initData()
  },
  initData() {
    const self = this;
    // 获取地址列表
    ModelMine.getAddressList()
      .then(res => {
        if (res.data.VipUserAddressList.length <= 0) {
          wx.removeStorageSync('addressId')
          self.data.empty = true
        }else{
          self.data.empty = false
        }
        this.setData({
          empty:self.data.empty,
          address: res.data.VipUserAddressList
        })
        
        wx.stopPullDownRefresh()
      })
      .catch(err => {})
  },
  doDelAddress(e) {
    const self = this
    wx.showModal({
      title: '提示',
      content: '是否要删除该地址?',
      success(res) {
        if (res.confirm) {
          // 删除
          const id = e.currentTarget.dataset.id
          const index = e.currentTarget.dataset.index
          ModelMine.delAddress({ id: id })
            .then(res => {
              if (res.status == 200) {
                App.WxService.showToast({ title: '删除成功', icon: 'none' })
                // 更新数据 2018/12/19 取消每次删除成功重新刷新页面，改为页面数据变动不请求数据
                // self.initData()
                self.data.address.splice(index,1)
                self.setData({
                  address:self.data.address
                })
              }
            })
            .catch(err => {})
        } else if (res.cancel) {
        }
      }
    })
  },
  doEditAddress(e) {
    // 编辑地址
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/account/address/address-edit/index?id=${id}`
    })
  },
  doSetDefault(e) {
    // 设置默认地址
    const self = this;
    const id = e.currentTarget.dataset.id
    const index = e.currentTarget.dataset.index
    ModelMine.setDefaultAddress({ id: id }).then(res => {
      if (res.status == 200) {
        App.WxService.showToast({ title: '设置默认地址成功', icon: 'none' })
        // 更新数据
        // this.initData()
        for(var i in self.data.address){
          self.data.address[i].isDefault = 0;
        }
        self.data.address[index].isDefault = 1;
        self.setData({
          address:self.data.address
        })
      }
    })
  },
  tapToAddAddress() {
    wx.navigateTo({
      url: '/pages/account/address/address-edit/index'
    })
  },
  doSelectAdress(e) {
    // 选中地址
    const id = e.currentTarget.dataset.id
    // 跳转到上一个页面
    if (this.data.showArrow) {
      App.WxService.setStorageSync('addressId', id)

      App.WxService.navigateBack({
        delta: 1
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.onShow()
  }
})
